import React, { useState, useEffect } from 'react'
import { Select } from 'antd'

const { Option, OptGroup } = Select

function getFormatGroup (options) {
  const o = {}
  options.forEach(li => {
    if (!li.group) {
      li.group = '其他'
    }
    if (!o[li.group]) {
      o[li.group] = []
    }
    o[li.group].push(li)
  })
  return o
}

function renderMultiOptions (options) {
  const o = getFormatGroup(options)
  const keys = Object.keys(o)
  return keys.map((k, j) => {
    return (
      <OptGroup label={k} key={j}>
        {o[k].map((li, i) => {
          return <Option key={`${j}-${i}`} value={JSON.stringify(li)}>{li.title}</Option>
        })}
      </OptGroup>
    )
  })
}

function Main ({ value, onChange, options, config = {} }) {
  const [isGroup, setIsGroup] = useState(false)
  const [c, setC] = useState({})
  useEffect(() => {
    if (config) {
      const o = {}
      if (config.allowClear) {
        o.allowClear = true
      }
      if (config.multi) {
        o.mode = 'multiple'
      }
      setC(o)
      if (config.group) {
        setIsGroup(true)
      }
    }
  }, [config])
  return (
    <Select placeholder='请选择' value={value} onChange={onChange} {...c}>
      {isGroup ? renderMultiOptions(options) : options.map((li, i) => {
        return <Option key={i} value={JSON.stringify(li)}>{li.title}</Option>
      })}
    </Select>
  )
}

export async function formatValue (v) {
  const res = []
  if (v instanceof Array) {
    v.forEach(li => {
      try {
        res.push(JSON.parse(li))
      } catch (e) {
        console.error(e)
      }
    })
  } else if (v) {
    try {
      res.push(JSON.parse(v))
    } catch (e) {
      console.error(e)
    }
  }
  return JSON.stringify(res)
}

export function formatInitValue (v, config = {}) {
  const isMulti = config && config.multi
  if (v instanceof Array) {
    if (isMulti) {
      const l = v.map(li => {
        const o = JSON.stringify(li)
        return o
      })
      return l
    }
    if (v.length) {
      return JSON.stringify(v[0])
    }
  } else {
    return isMulti ? [] : undefined
  }
}

export default Main
